<template>
  <div class="tinymce-editor">
    <editor
      ref="editor"
      v-model="myValue"
      :init="init"
      :disabled="disabled"
      @onClick="onClick"
    />

    <el-dialog
      title="历史版本"
      :visible.sync="historyDialogVisible"
      width="80%"
      :fullscreen="true"
      :before-close="beforeClose"
      @open="historyOpen"
    >
      <el-row type="flex" class="row-bg" style="height: 100%;">
        <el-col :span="18" class="el-row--flex flex">
          <el-scrollbar>
            <div v-html="versionDetails"/>
          </el-scrollbar>
        </el-col>
        <el-col :span="6" class="el-row--flex flex">
          <el-scrollbar wrap-class=" versionList">
            <dl
              v-for="(version,index) in versionList"
              v-if="index != 0"
              :key="version.id"
              class="clearfix"
              @click="getVersionDetails(version.id)"
            >
              <dt>{{ version.description || version.updateTime }}</dt>
              <dd>
                <Popconfirm message="确认恢复到此版本" :confirm-callback="coverVisible" :data="version">
                  <template>
                    <span>恢复到此版本</span>
                  </template>
                </Popconfirm>
              </dd>
              <dd>
                <Popconfirm message="确认删除该版本" :confirm-callback="deleteVisible" :data="version">
                  <template>
                    <i class="el-icon-delete"/>
                  </template>
                </Popconfirm>
              </dd>
            </dl>
          </el-scrollbar>
        </el-col>
      </el-row>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button @click="$store.commit('index/set_historyDialogVisible', false)">取 消</el-button>
        <el-button
          type="primary"
          @click="$store.commit('index/set_historyDialogVisible', false)"
        >确 定</el-button>
      </span> -->
    </el-dialog>
  </div>
</template>
<script>
  import { pictureAdd } from '@/api/file'
  import tinymce from 'tinymce/tinymce'
  import Editor from '@tinymce/tinymce-vue'
  import 'tinymce/themes/silver'
  import 'tinymce/icons/default/icons'

  // 编辑器插件plugins
  // 更多插件参考：https://www.tiny.cloud/docs/plugins/
  import 'tinymce/plugins/image' // 插入上传图片插件
  import 'tinymce/plugins/media' // 插入视频插件
  import 'tinymce/plugins/table' // 插入表格插件
  import 'tinymce/plugins/lists' // 列表插件
  import 'tinymce/plugins/wordcount' // 字数统计插件
  import 'tinymce/plugins/autosave' // 自动存稿
  import 'tinymce/plugins/fullscreen' // 全屏
  // import 'tinymce/plugins/preview' // 预览
  import 'tinymce/plugins/save' // 保存
  import 'tinymce/plugins/autoresize' // 编辑器大小自适应

  import './history' // 历史记录
  import './preview' // 预览
  import './saveVersion' // 保存历史

  import {
    getFileDetails,
    updateHtml,
    getVersionList,
    getVersionDetails,
    coverVisible,
    deleteVisible
  } from '@/api/file'

  export default {
    components: {
      Editor
    },
    props: {
      value: {
        type: String,
        default: ''
      },
      disabled: {
        type: Boolean,
        default: false
      },
      plugins: {
        type: [String, Array],
        default:
          'lists image media table wordcount autosave fullscreen preview save history saveVersion'
      },
      toolbar: {
        type: [String, Array],
        default: 'fullscreen preview'
      },
      selectedFile: {
        type: Object,
        // 对象或数组默认值必须从一个工厂函数获取
        default: function() {
          return { id: '' }
        }
      },
      isUpdate: {
        type: Number,
        default: 1
      },
      readonly: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        versionList: [],
        versionDetails: '',
        init: {
          language_url: this.$relativePath + '/tinymce/langs/zh_CN.js', // public目录下
          language: 'zh_CN',
          skin_url: this.$relativePath + '/tinymce/skins/ui/oxide', // public目录下
          height: '100%',
          readonly: this.readonly,
          autoresize_on_init: true,
          file_picker_types: 'media',
          plugins: this.plugins, // 父组件传入 或者 填写个默认的插件 要选用什么插件都可以 去官网可以查到
          toolbar: this.toolbar, // 工具栏 我用到的也就是lists image media table wordcount 这些 根据需求而定
          autosave_prefix: 'tinymce-autosave-' + this.selectedFile.id,
          autosave_restore_when_empty: true,
          autosave_interval: '10s',
          autosave_retention: '5m',
          menubar: '',
          init_instance_callback: (editor) => {
            tinymce.activeEditor.getBody().setAttribute('contenteditable', !this.readonly)
          },
          // file_picker_callback: (cb, value, meta) => {
          //   console.log(cb, value, meta)
          //   if (meta.filetype == 'media') {
          //     const input = document.createElement('input')
          //     const fileid = this.selectedFile.id

          //     input.setAttribute('type', 'file')
          //     input.onchange = function() {
          //       const file = this.files[0]// 只选取第一个文件。如果要选取全部，后面注意做修改

          //       pictureAdd(file, fileid)
          //         .then(result => {
          //           console.log(result.url)
          //         })
          //         .catch(err => {
          //           console.log(err)
          //           console.log(err)
          //         })
          //     }
          //     // 触发点击
          //     input.click()
          //   }
          // },
          save_onsavecallback: () => {
            this.updateHtml()
          },
          images_upload_handler: (blobInfo, success, failure) => {
            const fileid = this.selectedFile.id
            pictureAdd(blobInfo.blob(), fileid)
              .then(result => {
                success(result.url)
              })
              .catch(err => {
                console.log(err)
                failure(err)
              })
          }
        },
        myValue: '',
        oldValue: '',
        timingSave: '',
        clickCount:0,
        lastClickTime:0,
      }
    },
    computed: {
      historyDialogVisible() {
        return this.$store.state.index.historyDialogVisible
      }
    },
    mounted() {
      tinymce.init({})
      this.getFileDetails()

      if (this.isUpdate === 1) {
        this.automatic()
      }
    },
    destroyed() {
      clearInterval(this.timingSave)
      this.$store.commit('index/set_historyDialogVisible', false)
    },
    methods: {
      automatic() {
        this.timingSave = setInterval(() => {
          if (this.myValue !== this.oldValue) {
            this.updateHtml()
          }
        }, 10000)
      },
      onClick(e) {
        const current = new Date().getTime();
        if (current - this.lastClickTime < 500){
          this.lastClickTime=0;
          this.$emit('onClick', e, tinymce)
        } else{
          this.lastClickTime = current;
        }
      },
      getHtml() {
        const editor = this.$refs.editor.editor
        const url = encodeURIComponent(editor.documentBaseURI.getURI())
        const html = `<!DOCTYPE html>
              <html>
              <head>
               <meta charset="UTF-8">
              <meta name="Generator" content="EditPlus®">
              <meta name="Author" content="">
              <meta name="Keywords" content="">
              <meta name="Description" content="">
                <link type="text/css" rel="stylesheet" href="${url}tinymce/skins/ui/oxide/content.min.css">
                <link type="text/css" rel="stylesheet" href="${url}skins/content/default/content.css">
              </head>

              <body id="tinymce" class="mce-content-body ">
               ${editor.getContent()}
              </body>
              </html>`

        return html
      },
      getFileDetails() {
        sessionStorage.fileid = this.selectedFile.id
        getFileDetails(this.selectedFile.id)
          .then(result => {
            const rx = /<body[^>]*>([\s\S]+?)<\/body>/i // /////////
            const m = rx.exec(result)
            this.myValue = m[1]
            this.oldValue = m[1]
          })
          .catch(err => {
            console.log(err)
          })
      },
      updateHtml() {
        const fileid = this.selectedFile.id
        updateHtml(fileid, this.getHtml())
          .then(result => {
            console.log(result)
          })
          .catch(err => {
            console.log(err)
          })
      },
      beforeClose(done) {
        this.$store.commit('index/set_historyDialogVisible', false)
        done()
      },
      historyOpen() {
        const fileid = this.selectedFile.id
        getVersionList(fileid)
          .then(result => {
            const { data } = result
            this.versionList = data
          })
          .catch(err => {
            console.log(err)
          })
      },
      getVersionDetails(id) {
        getVersionDetails(id)
          .then(result => {
            const rx = /<body[^>]*>([\s\S]+?)<\/body>/i // /////////
            const m = rx.exec(result)
            this.versionDetails = m[1]
            this.$forceUpdate()
          })
          .catch(err => {
            console.log(err)
          })
      },
      coverVisible(version) {
        coverVisible(version.id)
          .then(result => {
            this.myValue = this.versionDetails
            this.$store.commit('index/set_historyDialogVisible', false)
          })
          .catch(err => {
            console.log(err)
          })
      },
      deleteVisible(version) {
        deleteVisible(version.id)
          .then(result => {
            // this.$store.commit('index/set_historyDialogVisible', false)
            this.versionList.splice(
              this.versionList.findIndex(v => v.id === version.id),
              1
            )
            this.versionDetails = ''
            console.log(result)
          })
          .catch(err => {
            console.log(err)
          })
      }
    },
    watch:{
      oldValue(val){
        console.log('aaaaaaaaaaa')
      }
    }
  }
</script>

<style lang="scss">
  .tinymce-editor {
    width: 100%;
    // height: calc(100vh - 90px);

    .tox-tinymce {
      border: none;
    }

    .el-dialog__body {
      padding: 30px 20px;
      height: calc(100% - 54px);
    }

    .history {
      width: 300px;
      margin: 0;
      border-right: 1px solid #000;

      dt {
        font-size: 35px;
      }
    }

    .versionList {
      line-height: 25px;
      text-align: left;
      background: #f6f7f9;
      border-left: 1px solid #e4e5e7;
      text-indent: 10px;

      dl {
        border-bottom: 1px solid #e4e5e7;
        padding: 10px 0;
        position: relative;

        &:hover {
          background: #e9f3ff;
        }

        dd {
          width: 50%;
          display: inline-block;
          cursor: pointer;
          color: #76b0f3;
          margin: 0;
          float: left;
        }

        img {
          position: absolute;
          right: 10px;
          top: 10px;
          cursor: pointer;
        }
      }
    }
  }
</style>
